package com.zhazha.earlybird.dao;

import com.zhazha.earlybird.beans.MajorInfo;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class MajorDAO {
	
	private SQLiteDatabase mDatabase;
	private static final String MAJOR_TABLE = "major";
	
	private static final String MAJOR_ID 				= "id";
	private static final String MAJOR_NAME				= "name";
	
	private static final int MAJOR_ID_INDEX 			= 0;
	private static final int MAJOR_NAME_INDEX			= 1;
	
	MajorDAO(SQLiteDatabase db) {
		mDatabase = db;
	}
	
	
	public boolean insert(MajorInfo major) {
		
		try {
			ContentValues cv = new ContentValues();
			cv.put(MAJOR_ID, 	major.getId());
			cv.put(MAJOR_NAME, 	major.getName());
			
			this.mDatabase.insert(MAJOR_TABLE, null, cv);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
	}
	
	public boolean delete(int id) {
		try {
			String whereClause = "id=?";
			String[] whereArgs = {String.valueOf(id)};
			this.mDatabase.delete(MAJOR_TABLE, whereClause, whereArgs);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean update(int id, ContentValues cv) {
		try {
			String whereClause = "id=?";
			String[] whereArgs = {String.valueOf(id)};
			this.mDatabase.update(MAJOR_TABLE, cv, whereClause, whereArgs);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public MajorInfo queryById(int id) {
		MajorInfo major = null;
		
		try {
			String selection = "id=?";
			String[] selectionArgs = {String.valueOf(id)};
			Cursor c = this.mDatabase.query(MAJOR_TABLE, null, selection, selectionArgs, null, null, null);
			
			if(c.moveToFirst()) {
				major = new MajorInfo();
				major.setId(c.getInt(MAJOR_ID_INDEX));
				major.setName(c.getString(MAJOR_NAME_INDEX));
			}
			
			return major;
			
		}catch (Exception e) {
			e.printStackTrace();
			return major;
		}
	}

}
